package com.jeomo.mem.starter.timedtask;

import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 会员积分自动过期失效
 *
 * @author:Jackpot
 * @create 2020-12-29 14:39
 * @description:
 */
@Component
public class PointsAutoExpiredTimedTask {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private String TASK_NAME ="PointsAutoExpiredTimedTask";
    private String TASK_GROUP ="memberPoints";

    @Resource
    private Scheduler scheduler;//任务调度器

    @PostConstruct
    private void pointsAutoExpiredJob() throws SchedulerException, ParseException {

        CronExpression cronExpression = new CronExpression("0 0 0 * * ?");
        Date nextValidTimeAfter = cronExpression.getNextValidTimeAfter(new Date());
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(nextValidTimeAfter);
        String message="定时任务[自动处理过期的会员积分]设置完毕, 下次执行时间: "+format;
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
        TriggerKey triggerKey = new TriggerKey(TASK_NAME, TASK_GROUP);
        if (scheduler.checkExists(triggerKey)) {
            CronTrigger trigger = (CronTrigger)scheduler.getTrigger(triggerKey);
            trigger = trigger.getTriggerBuilder()
                    .withIdentity(triggerKey)
                    .withSchedule(cronScheduleBuilder)
                    .startNow()
                    .build();
            scheduler.rescheduleJob(triggerKey,trigger);
            logger.info(message);
            return;
        }
        // 2、构建Trigger实例
        Trigger trigger = TriggerBuilder.newTrigger().withIdentity(TASK_NAME, TASK_GROUP)
                .withSchedule(cronScheduleBuilder)
                .startNow()
                .build();
        // 3、创建JobDetail实例，并与Job类绑定
        JobDetail jobDetail = JobBuilder.newJob(PointsAutoExpiredJob.class)
                .withIdentity(TASK_NAME, TASK_GROUP).build();
        scheduler.scheduleJob(jobDetail, trigger);
        scheduler.start();
        logger.info(message);
    }

}
